/*
 * @Author: NtyAaron
 * @Date: 2021-03-23 14:46:41
 * @LastEditors: NtyAaron
 * @LastEditTime: 2021-06-23 14:26:27
 * @Description: file content
 * @FilePath: \dwq\pages\index\index.js
 */
const app = getApp()
import { getCityWeather, getLocationByCoordinate } from '../../api/pubService/pubService.js'
import { getStay } from '../../api/daysOfStay/daysOfStay'
import { login, saveUser, getPower } from '../../api/user/user'
import { getPosterList } from '../../api/advertisement/advertisement'
import { _t } from '../../i18n/base'
import { getTqDesc } from '../../i18n/tq'
import { getLangCityName } from '../../utils/cityJson'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'

Page({
  data: {
    isShow: false,
    appId: 'wx5eaba51509996aad',
    entryData: {},
    loginShow: false,
    oneLogin: true,
    userInfo: {},
    cityWeather: {},
    banner: {},
    centerList: [],
    lang: {},
    goFlag: '',
    getAdvertObj: {
      categoryType: '',
      language: '',
      posterName: '',
      posterType: 1,
      showType: 1,
      trafficType: '',
    },
    bannerList: [],
    adShow: true,
    seconds: 5,
    popupAd: [],
    isOverseas: false,
  },
  // 中间导航列表点击跳转
  async toPageHandle(e) {
    if (e.currentTarget.dataset.url == '/pages/taxes/taxes') {
      if (wx.getStorageSync('userId')) {
        wx.switchTab({
          url: e.currentTarget.dataset.url,
        })
      } else {
        this.setData({
          loginShow: true,
        })
      }
    } else if (e.currentTarget.dataset.url == '/pages/pubService/pubService') {
      let userId = wx.getStorageSync('userId')
      this.setData({
        goFlag: 2,
      })
      this.getPower({ userId })
    } else if (e.currentTarget.dataset.url == '/pages/interactionMap/interactionMap') {
      let mapUrl = `/pages/interactionMap/interactionMap?locaInfo=${JSON.stringify(this.data.locaInfo)}`
      wx.navigateTo({
        url: mapUrl,
      })
    } else {
      wx.navigateTo({
        url: e.currentTarget.dataset.url,
      })
    }
  },

  // 跳转大湾区预览
  toOverview() {
    wx.navigateTo({
      url: '/pages/overview/overview',
    })
  },
  // 跳转对接与联络
  toLiaison() {
    wx.navigateTo({
      url: '/pages/liaison/liaison',
    })
  },
  // 跳转商务支援
  toBusinessSupport() {
    wx.navigateTo({
      url: '/pages/businessSupport/businessSupport',
    })
  },
  //  跳转活动及培训
  toTrain() {
    wx.navigateTo({
      url: '/pages/train/train',
    })
  },
  // 跳转香港贸发局
  toHKtdc() {
    wx.navigateTo({
      url: '/pages/hktdc/hktdc',
    })
  },
  // 跳转政策
  toPolicy() {
    wx.navigateTo({
      url: '/pages/policy/policy',
    })
  },
  // 跳转资助及优惠
  toDiscounts(e) {
    let type = e.currentTarget.dataset.type
    wx.navigateTo({
      url: '/pages/discounts/discounts?type=' + type,
    })
  },
  // 跳转新增停留日数
  addTaxes() {
    let userId = wx.getStorageSync('userId')
    if (userId) {
      wx.navigateTo({
        url: '/pages/addTaxes/addTaxes',
      })
    } else {
      this.setData({
        loginShow: true,
      })
    }
  },
  // 跳转我的页面
  gotoMe() {
    let userId = wx.getStorageSync('userId')
    if (userId) {
      wx.navigateTo({
        url: '/pages/me/me',
      })
    } else {
      this.setData({
        loginShow: true,
      })
    }
  },
  // 跳转搜索
  gotoSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  // 跳转多语言界面
  changeLang() {
    wx.navigateTo({
      url: '/pages/lang/lang',
    })
  },
  // 跳转天气预报
  toWeatherHandle() {
    let userId = wx.getStorageSync('userId')
    this.setData({
      goFlag: 1,
    })
    this.getPower({ userId })
  },
  // 点击首页停留工具跳转页面
  toDayCounterHandle() {
    wx.switchTab({
      url: '/pages/taxes/taxes',
    })
  },
  // 获取天气
  async getCityWeather() {
    let locaInfo = await wx.getLocation({
      type: 'wgs84',
      altitude: false,
    })
    this.setData({
      locaInfo,
    })
    let { result } = await getLocationByCoordinate({
      lat: locaInfo.latitude,
      lng: locaInfo.longitude,
    })
    if (result) {
      if (result.ad_info.nation == '中国') {
        let cityName = result.ad_info.city
        let index = cityName.indexOf('特别行政区')
        if (index == -1) {
          index = cityName.indexOf('市')
        }
        let city = cityName.substring(0, index)
        let res = await getCityWeather(city)
        if (res.result.result) {
          res.result.result.future.map((e) => {
            e.weather = getTqDesc(e.wid)
          })
          res.result.result.city = getLangCityName(res.result.result.city)
          this.setData({
            cityWeather: res.result.result,
            isOverseas: false,
          })
          wx.setStorageSync('cityWeather', JSON.stringify(res.result.result))
        }
      } else {
        this.setData({
          isOverseas: true,
        })
      }
    }
  },
  // 获取位置权限
  async getPower(e) {
    let { result } = await getPower(e)
    if (result.secret != 1) {
      Dialog.confirm({
        message: this.data.lang['请先开启位置权限'],
        confirmButtonText: this.data.lang['确定'],
        cancelButtonText: this.data.lang['取消'],
      })
        .then(() => {
          wx.navigateTo({
            url: '/pages/my/setting/setting',
          })
        })
        .catch(() => {})
    } else {
      if (this.data.goFlag == 1) {
        wx.navigateTo({
          url: `/pages/weatherForecast/weatherForecast?isOverseas=${JSON.stringify(this.data.isOverseas)}`,
        })
      } else {
        // wx.navigateTo({
        //   url: `/pages/regionSelection/regionSelection?locaInfo=${JSON.stringify(
        //     this.data.locaInfo
        //   )}`,
        // })
        wx.navigateTo({
          url: `/pages/pubService/pubService?locaInfo=${JSON.stringify(this.data.locaInfo)}&&isOverseas=${JSON.stringify(this.data.isOverseas)}`,
        })
      }
    }
  },
  // 判断本地是否缓存有天气
  initWeather() {
    this.getCityWeather()
  },
  // 登录
  async userLogin({detail}) {
    let { code } = await wx.login()
    let data = {
      code,
      encryptedData: detail.encryptedData,
      iv: detail.iv,
    }

    let res = await login(data)
   
    if (res.result == 'AES解密失败!' || res.code > 299) {
      wx.showToast({
        title: '登录失败，请重新登录',
        icon: 'none',
      })
    } else {
      if (!res.result.avatarUrl || !res.result.nickName) {
        this.setData({
          oneLogin: false,
          userInfo: res.result,
        })
      } else {
        this.setData({
          loginShow: false,
        })
        wx.setStorageSync('userInfo', JSON.stringify(res.result))
        wx.setStorageSync('userId', res.result.userId)
      }
    }
  },
  // 手机号授权登录
  async phoneAuthorizedLoginHandle() {
    let { userInfo } = await wx.getUserProfile({ desc: '用于完善会员资料' })
    let user = {
      ...result,
      ...userInfo,
      sex: userInfo.gender,
      languageCopy: userInfo.language,
      userId: this.data.userInfo.userId,
      openId: this.data.userInfo.openId,
    }
    delete user.language
    let { result } = await saveUser(user)
    if (result.avatarUrl || result.nickName) {
      this.setData({
        loginShow: false,
      })
      wx.setStorageSync('userInfo', JSON.stringify(result))
      wx.setStorageSync('userId', result.userId)
      // this.initLoginStatus()
    } else {
      wx.showToast({
        title: '失败',
      })
    }
  },
  // 关闭授权弹窗
  onClose() {
    this.setData({
      loginShow: false,
    })
  },
  // 秒数倒计时
  countdownToSeconds() {
    let seconds = 5
    var timer = setInterval(() => {
      seconds--
      this.setData({
        seconds,
      })
      if (this.data.seconds == 0) {
        clearInterval(timer)
        this.setData({
          adShow: false,
        })
      }
    }, 1000)
  },
  // 手动关闭广告
  adShowClosedHandle() {
    this.setData({
      adShow: false,
    })
  },
  // 获取首页弹窗广告
  async getPopupAds() {
    this.setData({
      ['getAdvertObj.posterType']: 2,
      'getAdvertObj.language': wx.getStorageSync('lang'),
    })
    let { result } = await getPosterList(this.data.getAdvertObj)
    if (result.length > 0) {
      result.map((item) => {
        if (item.showType == 1) {
          item.picLink = `${app.globalData.host}/attach/showPic?attachId=${item.pic}`
        } else {
          item.videoUrl = item.url
        }
      })
      this.setData({
        popupAd: result,
      })
      this.countdownToSeconds()
    } else {
      this.setData({
        adShow: false,
      })
    }
  },
  // 点击广告
  adClickHandle(e) {
    let type = e.currentTarget.dataset.type
    if (type == 2) {
      let link = e.currentTarget.dataset.link
      wx.navigateTo({
        url: `../video/video?link=${JSON.stringify(link)}`,
      })
    }
  },
  loadData() {
    let _lan = _t()
    var data = {
      lang: _lan,
      centerList: [
        {
          name: _lan['健康资讯'],
          img: 'https://www.octoplusmedia.net/images/jiankang@2x.png',
          url: '/pages/health/health',
        },
        {
          name: _lan['公共服务'],
          img: 'https://www.octoplusmedia.net/images/gg@2x.png',
          url: '/pages/pubService/pubService',
        },
        {
          name: _lan['停留日数'],
          img: 'https://www.octoplusmedia.net/images/tl@2x.png',
          url: '/pages/taxes/taxes',
        },
        {
          name: _lan['互动地图'],
          img: 'https://www.octoplusmedia.net/images/dt@2x.png',
          url: '/pages/interactionMap/interactionMap',
        },
        {
          name: _lan['跨境交通'],
          img: 'https://www.octoplusmedia.net/images/jt@2x.png',
          url: '/pages/traffic/traffic',
        },
      ],
    }
    wx.setTabBarItem({
      index: 0,
      text: _lan['首页'],
    })
    wx.setTabBarItem({
      index: 1,
      text: _lan['停留日数'],
    })
    wx.setTabBarItem({
      index: 2,
      text: _lan['关于'],
    })
    wx.setTabBarItem({
      index: 3,
      text: _lan['帮助'],
    })
    this.setData(data)
  },
  // 初始化判断是否本地登陆过
  initLoginStatus() {
    let userId = wx.getStorageSync('userId')
    if (userId) {
      this.isStatus({ userId: userId })
      this.setData({
        loginShow: false,
      })
    } else {
      this.setData({
        loginShow: true,
      })
    }
  },
  // 获取停留日数状态
  async isStatus(e) {
    let { result } = await getStay(e)
    this.setData({
      entryData: result,
    })
    if (result) {
      this.setData({
        isShow: true,
      })
    } else {
      this.setData({
        isShow: false,
      })
    }
  },
  // 只调用一次
  onLoad() {
    let lang = wx.getStorageSync('lang')
    if (!lang) {
      wx.getSystemInfo({
        success: function (res) {
          if (res.language == 'zh_CN') {
            wx.setStorageSync('lang', 1)
            wx.setStorageSync('language', 'zh')
          } else if (res.language == 'en') {
            wx.setStorageSync('lang', 3)
            wx.setStorageSync('language', 'en')
          } else if (res.language == 'zh-HK' || res.language == 'zh-TW') {
            // 繁体？
            wx.setStorageSync('lang', 2)
            wx.setStorageSync('language', 'tw')
          } else {
            wx.setStorageSync('lang', 1)
            wx.setStorageSync('language', 'zh')
          }
        },
      })
    }
    this.getPopupAds()
    this.loadData()
    this.getPosterList()
    this.initWeather()
    this.initLoginStatus()
  },
  // 获取轮播图
  async getPosterList() {
    this.setData({
      ['getAdvertObj.posterType']: 1,
      'getAdvertObj.language': wx.getStorageSync('lang'),
    })
    let { result } = await getPosterList(this.data.getAdvertObj)
    if (result.length > 0) {
      result.map((item) => {
        item.bannerLink = `${app.globalData.host}/attach/showPic?attachId=${item.pic}`
      })
      this.setData({
        bannerList: result,
      })
    } else {
      this.setData({
        adShow: false,
      })
    }
  },
  // 进入页面就调用
  onShow() {
    if (wx.getStorageSync('loginShow')) {
      wx.removeStorageSync('loginShow')
      this.setData({
        loginShow: true,
      })
    }
    this.initLoginStatus()
  },
})
